package com.chinaandroiddev.adfreedetector;

import java.net.InetAddress;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;


public class Detector {

    /*
     * com.bigtincan.android.adfree/.FreeMe
     */
    private static final String ADFREE_PACKAGE_NAME = "com.bigtincan.android.adfree";
    private static final String ADFREE_MAIN_ACTIVITY = "com.bigtincan.android.adfree.FreeMe";
    
    public static boolean isAdFreeInstalled(Context context) {
        PackageManager pm = context.getPackageManager();        
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.setClassName(ADFREE_PACKAGE_NAME, ADFREE_MAIN_ACTIVITY);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> apps = pm.queryIntentActivities(mainIntent, 0);
        if (apps.size() == 1) {
            return true;
        } else {
            return false;
        }
    }
    
    public static boolean isHostAltered(Context context, String hostname) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo().isConnected()) {
            try {
                /*
                 * 127.0.0.1 analytics.admob.com
                 * 127.0.0.1 analytics.live.com
127.0.0.1 analytics.msn.com
127.0.0.1 c.googleanalitics.net
127.0.0.1 feedads.googleadservices.com
127.0.0.1 googleads.g.doubleclick.net
127.0.0.1 googleads2.g.doubleclick.net
                 */
                InetAddress addr = null;
                if (hostname != null && hostname.length() > 0) {
                    addr = InetAddress.getByName(hostname);
                } else {
                    addr = InetAddress.getByName("googleads.g.doubleclick.net");
                }
                if (addr.getHostAddress().equals("127.0.0.1")) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        } else { // no network connection, we dont care
            return false;
        }
    }
}